import { defineStore } from 'pinia';
import { getRootRoutes } from '@/router/router';
import type { RouteLocationNormalized, RouteRecordRaw } from 'vue-router';

/**
 * 注册router相关的store
 */
export const useTabsStore = defineStore('tabs', {
  state: () => ({
    /** tab显示的页面 [会持久化保存] */
    tabViews: [] as $TabbarRecordRaw[],
    /** 页面缓存的key */
    cacheKey: [] as string[],
  }),
  actions: {
    /**
     * 通过路径删除tabs
     */
    delTabsByPath(path: string) {
      const newPath = path || '';
      const index1 = this.tabViews.findIndex((item) => newPath === (item.fullPath || ''));
      const index2 = this.cacheKey.findIndex((item) => newPath === item);
      index1 >= 0 && this.tabViews.splice(index1, 1);
      index2 >= 0 && this.cacheKey.splice(index2, 1);
    },
    /**
     * 通过 路径修改 meta.title
     */
    editMateTitle(path: string, title: string) {
      const view = this.tabViews.find((item) => item.fullPath === path);
      if (view) {
        view.meta.title = title;
      }
    },
    /**
     * 通过view删除tabs
     */
    delTabsByView(view: $TabbarRecordRaw | RouteLocationNormalized) {
      const viewPath = view.fullPath || view.path || '';
      this.delTabsByPath(viewPath);
    },

    /**
     * 添加单个标签
     */
    addSingleTabs(view: RouteLocationNormalized | RouteRecordRaw): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        const tabViews: $TabbarRecordRaw[] = JSON.parse(JSON.stringify(this.tabViews));
        const cacheKey: string[] = JSON.parse(JSON.stringify(this.cacheKey));
        if (!getRootRoutes().includes(view.path || '')) {
          const viewPath = 'fullPath' in view ? view.fullPath : view.path;
          const index1 = tabViews.findIndex((v) => v.fullPath === viewPath);
          const index2 = cacheKey.findIndex((v) => v === viewPath);
          const page: $TabbarRecordRaw = {
            fullPath: 'fullPath' in view ? view.fullPath : view.path,
            path: view.path,
            name: String(view.name),
            meta: view.meta!,
          };
          let dh = '';
          if ('query' in view) {
            dh = view.query.dh ? (view.query.dh as string) : '';
          }
          let title = view.meta?.title || String(view.name);
          title = title.split('-')[0] || '';
          view.meta!.title = `${title}${dh ? '-' : ''}${dh}`;
          index1 >= 0 ? tabViews.splice(index1, 1, page) : tabViews.push(page);
          index2 >= 0 && cacheKey.splice(index2, 1);
          !page.meta?.noCache && cacheKey.unshift(page.fullPath);
          this.tabViews = tabViews;
          this.cacheKey = cacheKey.splice(0, 10); // 设置最多缓存页面的数量
          resolve(JSON.parse(JSON.stringify(this.tabViews)));
        }
      });
    },

    /**
     * 删除单个标签
     */
    delSingleTabs(view: $TabbarRecordRaw | RouteLocationNormalized): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        this.delTabsByView(view);
        resolve(JSON.parse(JSON.stringify(this.tabViews)));
      });
    },

    /**
     * 删除其他标签
     */
    delOthersTabs(view: $TabbarRecordRaw | RouteLocationNormalized): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        const viewPath = view.fullPath || view.path || '';
        this.tabViews = this.tabViews.filter((v) => v?.meta?.affix || v.fullPath === viewPath);
        resolve(JSON.parse(JSON.stringify(this.tabViews)));
      });
    },

    /**
     * 删除所有标签
     * @param delAffix - 是否删除所有固定的标签
     */
    delAllTabs(delAffix: boolean): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        this.tabViews = delAffix ? [] : this.tabViews.filter((tag) => tag?.meta?.affix);
        this.cacheKey = this.tabViews.map((item) => item.fullPath);
        resolve(JSON.parse(JSON.stringify(this.tabViews)));
      });
    },

    /**
     * 删除左边标签
     */
    delLeftTabs(view: $TabbarRecordRaw | RouteLocationNormalized): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        const viewPath = view.fullPath || view.path || '';
        const index = this.tabViews.findIndex((item) => item.fullPath === viewPath);
        if (index >= 0) {
          const tabs = this.tabViews.slice(0, index);
          tabs.forEach((tab) => {
            !tab.meta.affix && this.delTabsByView(tab);
          });
        }
        resolve(JSON.parse(JSON.stringify(this.tabViews)));
      });
    },

    /**
     * 删除右边标签
     */
    delRightTabs(view: $TabbarRecordRaw | RouteLocationNormalized): Promise<$TabbarRecordRaw[]> {
      return new Promise<$TabbarRecordRaw[]>((resolve) => {
        const viewPath = view.fullPath || view.path || '';
        const index = this.tabViews.findIndex((item) => item.fullPath === viewPath);
        if (index >= 0) {
          const tabs = this.tabViews.slice(index + 1);
          tabs.forEach((tab) => {
            !tab?.meta?.affix && this.delTabsByView(tab);
          });
        }
        resolve(JSON.parse(JSON.stringify(this.tabViews)));
      });
    },
  },

  /** 持久化储存 依赖 pinia-plugin-persistedstate 插件 */
  persist: {
    key: 'my_pinia_router',
    storage: window.sessionStorage,
  },
});
